import React, { Component } from 'react';
import { Alert } from 'antd';
import axios from './axios.config';
import Components from './component.config';
import JavascriptCommon from './javascript.common';

class _Defaultcomponent extends Component {
    render() {
        return (
            <Alert
                message="温馨提示"
                description="该组件正在构建中，暂时无法显示，敬请期待。"
                type="info"
                showIcon
            />
        );
    }
}

export default {
    init() {
        return new Promise((resolve, reject) => {
            if (sessionStorage.getItem("storage_permits")) {
                this._build(JSON.parse(sessionStorage.getItem("storage_permits")));
                resolve(this.routes);
            } else {
                axios.get("Http/Msg/HomeServer.ashx?method=Backend_MenuTree").then(res => {
                    if (res.data.flag === "True") {
                        this._build(res.data.result);
                        sessionStorage.setItem("storage_permits", JSON.stringify(res.data.result));
                        resolve(this.routes);
                    } else {
                        reject();
                    }
                }).catch(() => {
                    reject();
                });
            }
        });
    },
    _build(data) {
        this.routes = this._buildNode(null, data);
        this.routes.push({ path: "/error", component: Components["_Error"], hidden: true, leaf: true });
        this.source.push({ path: "/error", component: Components["_Error"], index: "_", parent: "_", name: "Error" });
    },
    _buildNode(parent, store) {
        let obj = new Array();
        store.forEach(item => {
            if (!item.ZK_PARENT) { item.ZK_PARENT = null; }
            if (item.ZK_PARENT === parent) {
                if (item.ZK_PATH !== "/" && item.ZK_ISLEAF === "1") {
                    this.source.push({
                        parent: parent,
                        index: item.ZK_ID,
                        name: item.ZK_NAME,
                        path: item.ZK_PATH,
                        component: Components[item.ZK_COMPONENT] || _Defaultcomponent
                    });
                }
                obj.push({
                    index: item.ZK_ID,
                    path: item.ZK_PATH,
                    component: Components[item.ZK_COMPONENT] || _Defaultcomponent,
                    name: item.ZK_NAME,
                    hidden: item.ZK_ISHIDDEN === "1",
                    iconCls: item.ZK_ICON,
                    leaf: item.ZK_ISLEAF === "1",
                    children: this._buildNode(item.ZK_ID, store)
                });
            }
        });
        return obj;
    },
    routes: new Array(),
    source: new Array()
}